﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Web.Security;
using Microsoft.WindowsAzure.ServiceRuntime;

namespace WebRole1
{
	public partial class Login : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{

		}

		/// <summary>
		/// Login as forum user
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		protected void btnLogin_Click(object sender, EventArgs e)
		{
			//The password of a user is salted and then encrypted with MD5
			//First: get the salt. It is stored in the ServiceConfiguration.cscfg file
			string passwordSalt = RoleEnvironment.GetConfigurationSettingValue("PasswordSalt");

			//Second: add the salt to the password, and then encrypt it. Later we compare it to the value stored in the database
			string hashedPW = FormsAuthentication.HashPasswordForStoringInConfigFile(txtPassword.Text.Trim() + passwordSalt, "MD5");

			SqlConnection conn = new SqlConnection(RoleEnvironment.GetConfigurationSettingValue("ConnectionString"));
			SqlCommand command = conn.CreateCommand();
			conn.Open();

			command.CommandText = "select id, username from users where username = '" + txtUsername.Text.Trim().ToUpper() + "' and password = '" + hashedPW + "'";

			SqlDataReader dr = command.ExecuteReader();

			if (dr.Read())
			{
				HttpCookie aCookie = new HttpCookie("ForumSettings");
				aCookie.Values["UserID"] = dr["id"].ToString();
				aCookie.Values["Username"] = dr["Username"].ToString();
				aCookie.Expires = DateTime.Now.AddDays(1);
				Response.Cookies.Add(aCookie);

				Response.Redirect("default.aspx");
			}
			else
			{
				lblWrongLogin.Visible = true;
			}

			conn.Close();

			Response.Redirect("default.aspx");
		}
	}
}